import axios from 'axios';
import { Conversation, ConversationQuery, Message, QAHistory, QARequest } from '../types/qa';

// API基础URL
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080/api';

// 问答API
export const qaApi = {
  /**
   * 向知识库提问
   */
  ask: async (question: string, knowledgeBaseId: number, topK?: number) => {
    const response = await axios.post(`${API_BASE_URL}/qa/ask`, {
      question,
      knowledgeBaseId,
      topK: topK || 3,
    });
    return response.data;
  },

  /**
   * 获取问答历史记录
   */
  getHistory: async (page: number = 1, size: number = 10) => {
    const response = await axios.get(`${API_BASE_URL}/qa/history`, {
      params: { page, size },
    });
    return response.data;
  },

  /**
   * 搜索问答历史记录
   */
  searchHistory: async (query: string, page: number = 1, size: number = 10) => {
    const response = await axios.get(`${API_BASE_URL}/qa/history/search`, {
      params: { query, page, size },
    });
    return response.data;
  },

  /**
   * 通过ID获取问答历史记录
   */
  getHistoryById: async (id: number) => {
    const response = await axios.get(`${API_BASE_URL}/qa/history/${id}`);
    return response.data;
  },

  /**
   * 创建会话
   */
  createConversation: async (knowledgeBaseId: number, title?: string) => {
    const response = await axios.post(`${API_BASE_URL}/conversations`, {
      knowledgeBaseId,
      title: title || `会话 ${new Date().toLocaleString()}`,
    });
    return response.data;
  },

  /**
   * 获取会话列表
   */
  getConversations: async (params?: ConversationQuery) => {
    const response = await axios.get(`${API_BASE_URL}/conversations`, { params });
    return response.data;
  },

  /**
   * 获取指定ID的会话
   */
  getConversationById: async (id: number) => {
    const response = await axios.get(`${API_BASE_URL}/conversations/${id}`);
    return response.data;
  },

  /**
   * 获取会话消息
   */
  getConversationMessages: async (conversationId: number) => {
    const response = await axios.get(`${API_BASE_URL}/conversations/${conversationId}/messages`);
    return response.data;
  },

  /**
   * 发送消息到会话
   */
  sendMessage: async (conversationId: number, content: string) => {
    const response = await axios.post(`${API_BASE_URL}/conversations/${conversationId}/messages`, {
      content,
      role: 'user',
    });
    return response.data;
  },

  /**
   * 删除会话
   */
  deleteConversation: async (id: number) => {
    const response = await axios.delete(`${API_BASE_URL}/conversations/${id}`);
    return response.data;
  },

  /**
   * 更新会话标题
   */
  updateConversationTitle: async (id: number, title: string) => {
    const response = await axios.put(`${API_BASE_URL}/conversations/${id}`, { title });
    return response.data;
  },
}; 